var regioncount = 1;
var oneclickprice;
/*总红包是有金额红包的多少倍，现在写死3倍，后期系统中获取*/
var multiple = 3;
var ex = /^\d+$/;

/****************初始化上传空间*************/
var $list_covers = $('#fileList_covers'),
    $list_resources = $('#fileList_resources'),
    $list_video = $('#fileList_video'),
    ratio = window.devicePixelRatio || 1,
    thumbnailWidth = 100 * ratio,
    thumbnailHeight = 100 * ratio,
    uploader_resources,
    uploader_covers,
    uploader_video;

/*广告封面上传*/
uploader_covers = WebUploader.create({
    auto: true,
    swf: ctx + '/static/plugins/webuploader/0.1.5/Uploader.swf',
    server: ctx + '/file/uploadPic',
    pick: '#filePicker_covers',
    fileSizeLimit: 400 * 1024, //400K
    duplicate :true,  
    accept: {
        title: 'Images',
        extensions: 'jpg,jpeg',
        mimeTypes: 'image/jpg,image/jpeg'
    }
});
// 当有文件被添加进队列的时候
uploader_covers.on('fileQueued', function(file) {
    var $list = $("#fileList_covers");
    $list.append('<div id="' + file.id + '" class="file-item item">' +
        //'<div class="info">' + file.name + '</div>' +
        '<p class="state">等待上传...</p>' +
        '</div>');
});
/*上传中*/
uploader_covers.on('uploadProgress', function(file, percentage) {
    var $li = $('#' + file.id),
        $percent = $li.find('.progress .progress-bar');
    // 避免重复创建
    if (!$percent.length) {
        $percent = $('<div class="progress progress-striped active">' +
            '<div class="progress-bar" role="progressbar" style="width: 0%">' +
            '</div>' +
            '</div>').appendTo($li).find('.progress-bar');
    }
    $li.find('p.state').text('上传中');
    $percent.css('width', percentage * 100 + '%');
});
/*上传成功*/
uploader_covers.on('uploadSuccess', function(file, response) {
    var $li;
    if (response.error == "0000") {
        $("#covers").val(response.datas);
        $li = $('<div id="' + file.id + '" class="file-item">' + '<img style="height:150px;" src="' + response.datas + '"></div>');
    } else {
        $li = $('<div id="' + file.id + '" class="file-item">' + '上传失败 </div>');
    }
    $list_covers.html($li);

});

uploader_covers.on('uploadError', function(file) {
    var $li = $('#' + file.id),
        $error = $li
        .find('div.error');
    if (!$error.length) {
        $error = $('<div class="error"></div>')
            .appendTo($li);
    }
    $error.text('上传失败');
});

uploader_covers.on('uploadComplete', function(file) {
    $('#' + file.id).find('.progress').remove();
});
//  验证大小
uploader_covers.on("error", function(type) {
    if (type == "F_DUPLICATE") {
        parent.layer.alert("请不要重复选择文件！");
    }
});

/*多张轮播图上传*/
uploader_resources = WebUploader.create({
    auto: true,
    swf: ctx + '/static/plugins/webuploader/0.1.5/Uploader.swf',
    server: ctx + '/file/uploadPic',
    pick: '#filePicker_resources',
    // 单个文件的大小限制
    fileSingleSizeLimit: 500 * 1024, //限制大小10M，单文件
    duplicate :true,  
    accept: {
        title: 'Images',
        extensions: 'jpg,jpeg',
        mimeTypes: 'image/jpg,image/jpeg'
    }
});

//当有文件被添加进队列的时候
uploader_resources.on('fileQueued', function(file) {
    var $list = $("#fileList_resources");
    $list.append('<div id="' + file.id + '" class="file-item item-waiting">' +
        //'<div class="info">' + file.name + '</div>' +
        '<p class="state">等待上传...</p>' +
        '</div>');
});

/*上传中*/
uploader_resources.on('uploadProgress', function(file, percentage) {
    var $li = $('#' + file.id),
        $percent = $li.find('.progress .progress-bar');
    // 避免重复创建
    if (!$percent.length) {
        $percent = $('<div class="progress progress-striped active">' +
            '<div class="progress-bar" role="progressbar" style="width: 0%">' +
            '</div>' +
            '</div>').appendTo($li).find('.progress-bar');
    }
    $li.find('p.state').text('上传中');
    $percent.css('width', percentage * 100 + '%');
});

/*上传成功*/
uploader_resources.on('uploadSuccess', function(file, response) {
    var $li;
    if (response.error == "0000") {
        $("#resource" + file.id).val(response.datas);
        $li = $('<div id="' + file.id + '" class="file-item"><a onclick="delpic(this)">删除</a><br/>' + '<img style="height:150px;" src="' + response.datas + '"><div class="info"><input type="hidden" value="' + response.datas + '" name="resources" id="resource' + file.id + '"/></div></div>');
    } else {
        $li = $('<div id="' + file.id + '" class="file-item">' + '上传失败 </div>');
    }
    $list_resources.append($li);
});

uploader_resources.on('uploadError', function(file) {
    var $li = $('#' + file.id),
        $error = $li
        .find('div.error');
    if (!$error.length) {
        $error = $('<div class="error"></div>').appendTo($li);
    }
    $error.text('上传失败');
});

uploader_resources.on('uploadComplete', function(file) {
    $('#' + file.id).find('.progress').remove();
    $('#' + file.id).find('p.state').remove();
    $('#' + file.id).remove();
});

//  验证大小
uploader_resources.on("error", function(type) {
    if (type == "F_DUPLICATE") {
        parent.layer.alert("请不要重复选择文件！");
    }
});


/*视频上传*/
uploader_video = WebUploader.create({
    auto: true,
    swf: ctx + '/lib/webuploader/0.1.5/Uploader.swf',
    server: ctx + '/file/uploadPic',
    pick: '#filePicker_video',
    fileSizeLimit: 2 * 1024 * 1024, //2M
    accept: {
        title: 'Images',
        extensions: 'wmv,3gp,mp4,rmvb,mov,avi,m4v',
        mimeTypes: 'video/mp4,video/3gp,video/rmvb,video/mov,video/avi,video/wmv,audio/mp3'
    },
    formData: {
        foldername: ''
    }
});

uploader_video.on('fileQueued', function(file) {
    var $li = $('<div id="' + file.id + '" class="file-item">' + '<img><div class="info">' + file.name + '</div></div>'),
        $img = $li.find('img');

    $list_video.append($li);
    uploader_video.makeThumb(file, function(error, src) {
        if (error) {
            $img.replaceWith('<span>不能预览</span>');
            return;
        }

        $img.attr('src', src);
    }, thumbnailWidth, thumbnailHeight);
});

uploader_video.on('uploadSuccess', function(file, response) {
    var $li;
    if (response.error == "0000") {
        $("#video").val(response.datas);
        $li = $('<div id="' + file.id + '" class="file-item">' + '<img src="' + response.datas + '?vframe/png/offset/3/"></div>');
    } else {
        $li = $('<div id="' + file.id + '" class="file-item">' + '上传失败 </div>');
    }
    $list_video.html($li);
});

uploader_video.on('uploadError', function(file) {
    var $li = $('#' + file.id),
        $error = $li.find('div.error');
    if (!$error.length) {
        $error = $('<div class="error"></div>').appendTo($li);
    }
    $error.text('上传失败');
});

uploader_video.on('uploadComplete', function(file) {
    $('#' + file.id).find('.progress').remove();
});

//  验证大小
uploader_video.on("error", function(type) {
    if (type == "F_DUPLICATE") {
        parent.layer.alert("请不要重复选择文件！");
    }
});


/******************************************/

function changeType(value) {
    if (value == "1") {
        $("#videourl").show();
        $("#imgresources").hide();
    } else {
        $("#videourl").hide();
        $("#imgresources").show();
    }
    $("#oneclickprice").val($('#resource_type option:selected').attr("data_price"))
    updatecount();
}

/*更新红包的曝光次数和点击测试*/
function updatecount() {
    if ($("#total_amount").val() != "" && !isNaN($("#total_amount").val())) {
        oneclickprice = $("#oneclickprice").val();
        var clickcount = parseFloat($("#total_amount").val()) / parseFloat(oneclickprice);
        $("#clickcount").val(clickcount);
        $("#count").val(clickcount * multiple);
    }
}

$(document).ready(function() {
    regioncount = $("#regiondiv").children().length;
    oneclickprice = $("#oneclickprice").val();
    regioncount = $("#regiondiv").children().length;
    /*失去焦点事件，更新点击次数和曝光次数*/
    $("#total_amount").blur(function() {
        updatecount();
    });

    changeAreaType($("#isarea option:selected").val());
});

function edittext() {
    $("#eg").addClass("no-padding");
    $(".click2edit").summernote({
        lang: "zh-CN",
        focus: true
    })
};

function savetext() {
    $("#eg").removeClass("no-padding");
    var aHTML = $(".click2edit").code();
    $(".click2edit").destroy();
    alert(aHTML);
};

function save() {
    $.ajax({
        type: "post",
        url: "bonus-add",
        data: $("#member_table_form").serialize(),
        error: function(jqXHR, textStatus, errorThrown) {
            layer.msg("系统异常", { icon: 5, time: 1000 });
        },
        success: function(msg) {
            var info = eval('(' + msg + ')');
            if (info.error == '0000') {
                location.href = "${ctx}/createadvertorder?advertid=" + info.datas;
            } else {
                layer.msg(info.information, { icon: 5, time: 1000 });
                var index = parent.layer.getFrameIndex(window.name);
                parent.$('.btn-refresh').click();
                parent.layer.close(index);
            }
        }
    })
}

function addregion() {
    regioncount++;
    var html = '<div class="row cl"><label class="col-sm-2"></label>' + '<div class="col-sm-4">' + '<input id="city-picker' + regioncount + '" class="form-control" readonly name="regioninfo" type="text" value="" data-toggle="city-picker">' + '</div><div class="col-sm-1"><button onclick="delregion(this)" class="btn btn-danger radius"  type="button">删除</button></div></div>';
    $("#regiondiv").append(html);
    var $newcitypicker = $('#city-picker' + regioncount);
    $newcitypicker.citypicker();
    $('#reset').click(function() {
        $newcitypicker.citypicker('reset');
    });

    $('#destroy').click(function() {
        $newcitypicker.citypicker('destroy');
    });

    if (regioncount > 1) {
        $("#range").hide();
        cleanlocationinfo();
    }
}

function delpic(obj) {
    $(obj).parent().remove();
}

function cleanlocationinfo() {
    $("#longitude").val("");
    $("#latitude").val("");
    $("#distance_range").val("");
}

function delregion(obj) {
    $(obj).parent().parent().remove();
    regioncount = $("#regiondiv").children().length;
    if (regioncount == 1) {
        $("#range").show();
    }
}

function getlnglat() {
    var index = layer.open({
        type: 2,
        title: "地图定位",
        content: "baiduditu?lng=" + $("#longitude").val() + "&lat=" + $("#latitude").val()
    });
    layer.full(index);
}

function loadlnglat(lng, lat) {
    $("#longitude").val(lng);
    $("#latitude").val(lat);
}

function addkeyword() {
    $("#keywordsidv").append('<input type="text" class="form-control input-keyword" value="" placeholder="输入关键字" name="keyword">');
}

function cancel() {
    var index = parent.layer.getFrameIndex(window.name);
    if (index) {
        window.parent.location.reload(); //刷新父页面
        parent.layer.close(index);
    }
}

function save() {
    if (!ex.test($("#clickcount").val())) {
        parent.layer.alert("点击次数必须是整数", {
            icon: 2,
            skin: 'layer-ext-moon'
        })
        return;
    }
    if ($("#resource_type").val() == -1) {
        parent.layer.alert("请选择投放类型", {
            icon: 2,
            skin: 'layer-ext-moon'
        })
        return;
    } else if ($("#resource_type").val() == 0) {
        if ($("input[name='resources']").length != 3) {
            parent.layer.alert("图片红包得轮播图需要3张", {
                icon: 2,
                skin: 'layer-ext-moon'
            })
            return;
        }
    } else if (!ex.test($("#clickcount").val())) {
        parent.layer.alert("点击次数必须是整数", {
            icon: 2,
            skin: 'layer-ext-moon'
        })
        return;
    }
    $.ajax({
        type: "post",
        url: "bonus-add",
        data: $("#table_form").serialize(),
        success: function(msg) {
            var info = eval('(' + msg + ')');
            if (info.error == '0000') { //添加或修改成功
                var advertid = info.datas;
                if ($("#id").val() == null || $("#id").val() == "") {
                    window.location.href = "dingdan/createadvertorder?advertid=" + advertid;
                } else {
                    layer.msg(info.information, {
                        icon: 5,
                        time: 1000
                    });
                    var index = parent.layer
                        .getFrameIndex(window.name);
                    parent.$('.btn-refresh').click();
                    parent.layer.close(index);
                }
            } else {
                parent.layer.alert(info.information, {
                    icon: 2,
                    skin: 'layer-ext-moon'
                })
            }
        }
    })
}

function changeAreaType(value) {
    if (value != 1) {
        $("#regiondiv").hide();
        $("#range").hide();
    } else {
        $("#regiondiv").show();
        regioncount = $("#regiondiv").children().length;
        if (regioncount == 1) {
            $("#range").show();
        }
    }
}
